package com.gzhryc.shared_device.oem.h5.mng.controllers.device;

import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class DeviceController {

    static Logger log = Logger.getLogger(DeviceController.class);

    @Route(value = { "/device/list.html" })
    public String list(HttpServletRequest request) {
        return "/device/list.html";
    }

    @Route(value = "/device/list.data")
    public ListResult<Device> listData(HttpServletRequest request) {
        ListResult<Device> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        DeviceSearch search = WebUtils.getParameter(request, DeviceSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(DeviceService.self().countBySearch(search));
        result.getBody().setData(DeviceService.self().findBySearch(search, pageNo, pageLimit));
        if(result.getBody().getData() != null && result.getBody().getData().size() > 0){
            result.setCode(DtoConstants.SUCCESS,null);
        }
        return result;
    }

    @Route(value = { "/device/add.html" })
    public String add(HttpServletRequest request) {
        return "/device/edit.html";
    }

    @Route(value = { "/device/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        Device device = WebUtils.getParameter(request, Device.class);
        try {
            if (DeviceService.self().add(device)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/device/info.html" })
    public String info(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        Device device = DeviceService.self().getByDeviceSn(deviceSn);
        WebUtils.setAttribute(request,device);
        return "/device/info.html";
    }

    @Route(value = { "/device/func/info.html" })
    public void funcInfo(HttpServletRequest request,HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        String funCode = WebUtils.getString(request,"funCode");
        if(EDeviceFunCode.CDCZ.index().equals(funCode)){
            WebUtils.sendRedirect(request,response,"/cdcz/device/info.html?deviceSn="+deviceSn);
        }else if(EDeviceFunCode.CDB.index().equals(funCode)){
            WebUtils.sendRedirect(request,response,"/cdb/device/info.html?deviceSn="+deviceSn);
        }else if(EDeviceFunCode.BXSCN.index().equals(funCode)){
            WebUtils.sendRedirect(request,response,"/bxscn/device/info.html?deviceSn="+deviceSn);
        }else if(EDeviceFunCode.PCL.index().equals(funCode)){
            WebUtils.sendRedirect(request,response,"/pcl/device/info.html?deviceSn="+deviceSn);
        }
    }

    @Route(value = { "/device/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        Device device = WebUtils.getParameter(request, Device.class);
        try {
            Device temp = DeviceService.self().getByDeviceSn(device.getDeviceSn());
            if(temp == null){
                result.setMsg("未找到设备信息");
                return result;
            }

            if(device.getUserId() != null) {
                if (temp.getUserId() == null || !temp.getUserId().equals(device.getUserId())){
                    User user = UserService.self().getById(device.getUserId());
                    if(user == null){
                        result.setMsg("未找到归属人信息");
                        return result;
                    }

                    device.setUserName(user.getName());
                    device.setUserPhone(user.getPhone());
                    device.setBelongDate(new Date());
                }
            }

            if (DeviceService.self().updateNotNull(device)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/device/qrcode.html" })
    public String qrcode(HttpServletRequest request, HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        Device device = DeviceService.self().getByDeviceSn(deviceSn);
        if(device != null) {
            List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(device.getDeviceTypeId());
            if(deviceTypeFuncList != null && deviceTypeFuncList.size() == 1){
                DeviceTypeFunc deviceTypeFunc = deviceTypeFuncList.get(0);
                if(EDeviceFunCode.CDCZ.index().equals(deviceTypeFunc.getCode())){
                    WebUtils.sendRedirect(request,response,"/cdcz/device/qrcode.html?deviceSn="+deviceSn);
                    return null;
                }else if(EDeviceFunCode.CDB.index().equals(deviceTypeFunc.getCode())){
                    WebUtils.sendRedirect(request,response,"/cdb/device/qrcode.html?deviceSn="+deviceSn);
                    return null;
                }else if(EDeviceFunCode.BXSCN.index().equals(deviceTypeFunc.getCode())){
                    WebUtils.sendRedirect(request,response,"/bxscn/device/qrcode.html?deviceSn="+deviceSn);
                    return null;
                }else if(EDeviceFunCode.PCL.index().equals(deviceTypeFunc.getCode())){
                    WebUtils.sendRedirect(request,response,"/pcl/device/qrcode.html?deviceSn="+deviceSn);
                    return null;
                }
            }

            String httpDomain = PropertyTools.get().getString("httpDomain");
            String url = httpDomain + "/dev/auto/" + device.getDeviceSn();
            request.setAttribute("url", url);
        }
        return "/device/qrcode.html";
    }

    @Route(value = { "/device/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            try {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/dev/auto/" + deviceSn;
                WebUtils.exportJPEG(response);
                MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @Route(value = { "/device/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if (StringTools.isNotBlank(deviceSn)) {
            try {
                if (DeviceService.self().deleteByDeviceSn(deviceSn)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
}
